﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TankMovement1 : MonoBehaviour
{
    public int m_PlayerNum = 1;
    public float m_Speed = 12f;
    public float m_TurnSpeed = 180f;
    public AudioSource m_MovementAudio;
    public AudioClip m_DrivingClip;
    public AudioClip m_IdlingClip;
    public float m_PitchRange = 0.2f;

    private Rigidbody m_Rigidbody;
    public string m_MovementAxisName;
    public string m_TurnAxisName;
    public float m_InputMovementValue;
    public float m_InputTurnValue;
    private float m_OriginalPitch;

    private void Awake()
    {
        m_Rigidbody = GetComponent<Rigidbody>();
    }

    private void OnEnable()
    {
        m_Rigidbody.isKinematic = false;
        m_InputMovementValue = 0f;
        m_InputTurnValue = 0f;

    }

    private void OnDisable()
    {
        m_Rigidbody.isKinematic = true;
    }
    private void Start()
    {
        m_MovementAxisName = "Vertical" + m_PlayerNum;
        m_TurnAxisName = "Horizontal" + m_PlayerNum;
        m_OriginalPitch = m_MovementAudio.pitch;

    }
    private void Update()
    {
        m_InputMovementValue = Input.GetAxis(m_MovementAxisName);
        m_InputTurnValue = Input.GetAxis(m_TurnAxisName);
        EngineAudio();
    }

    void EngineAudio()
    {
        if(Mathf.Abs(m_InputMovementValue) < 0.1f && Mathf.Abs(m_InputTurnValue) < 0.1f)
        {
            if(m_MovementAudio.clip != m_IdlingClip)
            {
                m_MovementAudio.clip = m_IdlingClip;
                m_MovementAudio.pitch = Random.Range(m_OriginalPitch - m_PitchRange, m_OriginalPitch + m_PitchRange);
                m_MovementAudio.Play();
            }
        }
        else
        {
            if (m_MovementAudio.clip != m_DrivingClip)
            {
                m_MovementAudio.clip = m_DrivingClip;
                m_MovementAudio.pitch = Random.Range(m_OriginalPitch - m_PitchRange, m_OriginalPitch + m_PitchRange);
                m_MovementAudio.Play();
            }
        }
    }

    private void FixedUpdate()
    {
        Move();
        Turn();
    }

    void Move()
    {
        Vector3 move = transform.forward * m_InputMovementValue * m_Speed * Time.deltaTime;
        m_Rigidbody.MovePosition( m_Rigidbody.position + move);
    }

    void Turn()
    {
        float turn = m_InputTurnValue * m_TurnSpeed * Time.deltaTime;
        Quaternion turnRotation = Quaternion.Euler(0f, turn, 0f);
        m_Rigidbody.MoveRotation( m_Rigidbody.rotation * turnRotation);
    }
}
